<script setup lang="ts">
import { ref, getCurrentInstance, onMounted, watch, computed, onUnmounted } from 'vue'
import HoverDropdown from './common/HoverDropdown.vue';
import GuideCoinContract from './GuideCoinContract.vue';
import { useCoinStore } from '@/store/coin';
import { useThemeStore } from '@/store/theme';
import { userStore } from '@/store/user';
import { getFundingRate } from '@/apis/hycurrency'
import { CoinItem } from "@/interfaces/currency.js";
import { formatNumberWithThousands } from '@/utils/utils';
const props = defineProps(['domInfo'])
const instance = getCurrentInstance()
const coinInfoDom = ref()
const isContentOverflowValue = ref(false)
const scrollLeft = ref(0)
const scrollWidth = ref(0)
const isHover = ref<boolean>(false)
const currencyId = ref<string>()
const isLoading = ref<boolean>(true)
const lastFundingRate = ref('')
const timer = ref()
const timer1 = ref()
const secodess = ref(0)
const secode = ref('')
const priceInfo = computed(() => {
    return useCoinStore().getPrice(useCoinStore().coinInfo.name)
})
let hycurrencySocket: any
// 
const coinInfo = ref<CoinItem>({
    src: '',
    percentText: '',
    currencyPair: '',
    amount: 0,
    externalPrice: 0,
    timestamp: 0,
    percent: 0,
    usdAmount: 0,
    cnyAmount: 0,
    hkdAmount: 0,
    eurAmount: 0,
    lowest: 0,
    highest: 0,
    open: 0,
    total: 0,
    checked: false,
    markPrice: 0,
})

// const connectCurrency = () => {
//     if (currencyId.value) {
//         hycurrencySocket.unsubscribe(currencyId.value, '/topic/market')
//     }
//     currencyId.value = Date.now().toString(36) + Math.floor(Math.random() * 1000).toString(36)

//     hycurrencySocket.subscribe(currencyId.value, `/topic/market`, (data: CoinItem) => {
//         if (data.currencyPair === useCoinStore().coinInfo.name + '-USDT') {
//             coinInfo.value = data
//             isLoading.value = false
//             setTimeout(() => {
//                 if (scrollLeft.value) {
//                     scrollFn('left')
//                 }
//                 isContentOverflow()
//             }, 100);
//         }
//     })
// }

const addLove = () => {
    if (userStore().loveList.includes(useCoinStore().coinInfo.name)) {
        userStore().remvoeLoveItem(useCoinStore().coinInfo.name)
    } else {
        userStore().addLoveItem(useCoinStore().coinInfo.name)
    }
}
const getSrc = () => {
    return useCoinStore().logoList ? 'https://file.uhx.io/' + (useCoinStore().logoList as Record<string, string>)[useCoinStore().coinInfo.name] : ''
}

const hoverFn = () => {
    isHover.value = true
}

const leaveFn = () => {
    isHover.value = false
}
const isContentOverflow = () => {
    if (!coinInfoDom.value) return false;
    const container = coinInfoDom.value;
    const containerWidth = container.clientWidth;
    const children = container.children as unknown as HTMLElement[];
    let totalChildrenWidth = 0;
    for (let i = 0; i < children.length; i++) {
        if (children[i].classList.contains('item')) {
            totalChildrenWidth += children[i].offsetWidth;
        }
    }
    totalChildrenWidth += 4 * 15.5;
    scrollWidth.value = totalChildrenWidth - containerWidth
    isContentOverflowValue.value = totalChildrenWidth > containerWidth;
};
const scrollFn = (type: string) => {
    const container = document.getElementById('aaa') as unknown as HTMLElement;
    scrollLeft.value = type === 'left' ? 99999 : 0
    container.scrollTo({
        left: scrollLeft.value,
        behavior: 'smooth'
    })
}
const emit = defineEmits(['showCoinInfo'])
const showCoinInfo = () => {
    emit('showCoinInfo')
}
function formatMsToTime(milliseconds: any) {
    // 1. 毫秒转总秒数（向下取整，忽略毫秒部分）
    const totalSeconds = Math.floor(milliseconds / 1000);

    // 2. 拆分小时、分钟、秒
    const hours = Math.floor(totalSeconds / 3600);
    const remainingSeconds = totalSeconds % 3600;
    const minutes = Math.floor(remainingSeconds / 60);
    const seconds = remainingSeconds % 60;

    // 3. 补零（确保每个单位为两位数）
    const pad = (num: any) => num.toString().padStart(2, '0');

    return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
}
const getInfo = async () => {
    timer.value && clearTimeout(timer.value)
    timer1.value && clearTimeout(timer1.value)
    const data = await getFundingRate({ currencyPair: useCoinStore().coinInfo.name + '-USDT' })
    lastFundingRate.value = data.lastFundingRate as string
    const secodes = new Date().getTime() - data.nextFundingTime
    secodess.value = secodes
    if (secodes < 0) {
        secode.value = formatMsToTime(0)
        secodess.value = 0
    } else {
        if (secodes > 0) {
            timer1.value = setInterval(() => {
                secode.value = formatMsToTime(secodess.value)
                secodess.value -= 1000
            }, 1000)
        } else {
            clearInterval(timer1.value)
            secode.value = formatMsToTime(0)
        }
    }
    timer.value = setInterval(async () => {
        const data = await getFundingRate({ currencyPair: useCoinStore().coinInfo.name + '-USDT' })
        lastFundingRate.value = data.lastFundingRate as string
        const secodes = new Date().getTime() - data.nextFundingTime
        secodess.value = secodes
        if (secodes < 0) {
            secode.value = formatMsToTime(0)
            secodess.value = 0
        } else {
            if (secodes > 0) {
                timer1.value = setInterval(() => {
                    secode.value = formatMsToTime(secodess.value)
                    secodess.value -= 1000
                }, 1000)
            } else {
                clearInterval(timer1.value)
                secode.value = formatMsToTime(0)
            }
        }
    }, 30000)
}
watch(() => props.domInfo, (v) => {
    isContentOverflow()
})
// watch(() => userStore().hycurrencySocket, (val) => {
//     if (val) {
//         if (instance) {
//             hycurrencySocket = instance.appContext.config.globalProperties.$hycurrencySocket
//             if (hycurrencySocket.connected) {
//                 connectCurrency()
//             }
//         }
//     }
// }, { immediate: true })
onMounted(() => {
    getInfo()
})
onUnmounted(() => {
    timer.value && clearTimeout(timer.value)
    timer1.value && clearTimeout(timer1.value)
    if (hycurrencySocket) {
        hycurrencySocket.unsubscribe(currencyId.value, '/topic/market')
    }
})
watch(() => useCoinStore().coinInfo.name, () => {
    getInfo()
    isLoading.value = true
})
watch(() => useCoinStore().contractKLine, (val) => {
    if (val) {
        isLoading.value = false
        coinInfo.value = val[useCoinStore().coinInfo.name + '-USDT']
    }
}, {
    deep: true
})
</script>
<template>
    <div class="h-full px-[16px] flex items-center flex-nowrap" :class="[isLoading ? 'justify-center' : '']">
        <div v-show="!isLoading" class="hidden sm:flex items-center ">
            <div @click="addLove"
                class="w-[24px] mr-[4px] h-[24px] border-solid border-[1px] cursor-pointer border-[#ededed] dark:border-[#333b47] rounded-[6px] flex items-center justify-center">
                <span
                    :class="[userStore().loveList.includes(useCoinStore().coinInfo.name) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                    class="iconfont text-[16px]"></span>
            </div>
            <img class="w-[24px] m-[4px]" :src="getSrc()" />
            <HoverDropdown class="hidden md:block sm:block lg:block " @mouseenter="hoverFn" @mouseleave="leaveFn"
                :horizontal-offset-value="-78" :vertical-offset-value="5">
                <div class="m-[4px]">
                    <div class="text-[20px] text-black font-bold dark:text-[#EAECEF]">
                        <span>{{
                            useCoinStore().coinInfo.name
                            }}/USDT</span>
                        <span class="text-[12px] font-normal ml-[6px] bg-[#f5f5f5] px-[4px] py-[1px]">永续</span>
                        <span class="iconfont ml-[6px] text-[12px]"
                            :class="[isHover ? 'icon-xiangshang' : 'icon-xiangxia']"></span>
                    </div>
                    <div class="text-[#9c9c9c] text-[12px] dark:text-[#707A8A]">UHX价格</div>
                </div>
                <template #content>
                    <div class="w-[320px] box-border overflow-hidden ">
                        <GuideCoinContract />
                    </div>
                </template>
            </HoverDropdown>
            <div class="ml-[10px] mr-[16px] relative">
                <div v-if="isContentOverflowValue && scrollLeft" @click="scrollFn('right')"
                    :style="{ background: useThemeStore().theme === 'light' ? `linear-gradient(270deg, #fff 0%, #fff calc(24px / 2), transparent 100%)` : `linear-gradient(270deg, #181a20 0%, #181a20 calc(24px / 2), transparent 100%)` }"
                    class=" absolute right-[-28px] cursor-pointer w-[12px] h-[38px] flex items-center z-[10]">
                    <span
                        class="iconfont icon-zuo font-bold  hover:text-[black] text-[#9C9C9C] text-[12px] dark:hover:text-[#EAECEF] dark:text-[#707A8A]"></span>
                </div>
                <div class="text-[20px] font-bold" :class="[coinInfo.percent > 0 ? 'text-rise' : 'text-fall']">{{
                    priceInfo?.unitDecimals ? formatNumberWithThousands(coinInfo.amount.toFixed(priceInfo.unitDecimals))
                        :
                        formatNumberWithThousands(coinInfo.amount) }}</div>
                <div class="text-[12px] text-black dark:text-[#EAECEF] ">${{
                    priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo.externalPrice.toFixed(priceInfo.unitDecimals))
                        :
                        formatNumberWithThousands(coinInfo.externalPrice) }}
                </div>
            </div>
        </div>
        <div v-show="!isLoading" id="aaa" class="hidden overflow-hidden relative sm:flex">
            <div v-if="isContentOverflowValue && !scrollLeft" @click="scrollFn('left')"
                :style="{ background: useThemeStore().theme === 'light' ? `linear-gradient(270deg, #fff 0%, #fff calc(24px / 2), transparent 100%)` : `linear-gradient(270deg, #181a20 0%, #181a20 calc(24px / 2), transparent 100%)` }"
                class="absolute right-[0] z-[20] h-[100%] flex items-center w-[12px]  justify-center cursor-pointer">
                <span
                    class="iconfont icon-you text-[12px] font-bold hover:text-[black] text-[#9C9C9C] dark:hover:text-[#EAECEF] dark:text-[#707A8A]"></span>
            </div>
            <div class="flex flex-nowrap " ref="coinInfoDom">
                <!-- <div class="flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">标记价格</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo.markPrice.toFixed(
                            priceInfo?.unitDecimals)) : formatNumberWithThousands(coinInfo.markPrice) }}</div>
                </div> -->
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item mr-[16px]">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">资金费率/倒计时</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ Number(lastFundingRate) * 100 || '--'
                        }}%/{{
                            secode
                            ||
                            '--' }}
                    </div>
                </div>
                <div class="flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h涨跌</div>
                    <div class="text-[12px] mt-[6px] " :class="[coinInfo.percent > 0 ? 'text-rise' : 'text-fall']">
                        <span>{{ coinInfo.percent > 0 ? '+' : '' }}{{ Number(coinInfo.percent * 100).toFixed(2)
                            }}%</span>
                    </div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h最高价</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo.highest.toFixed(
                            priceInfo?.unitDecimals)) : formatNumberWithThousands(coinInfo.highest) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h最低价</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(coinInfo.lowest.toFixed(priceInfo?.unitDecimals)) :
                        formatNumberWithThousands(
                            coinInfo.lowest) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h成交量({{ useCoinStore().coinInfo.name
                    }})</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.coinDecimals ?
                        formatNumberWithThousands(coinInfo.total.toFixed(priceInfo?.coinDecimals)) :
                        formatNumberWithThousands(coinInfo.total) }}</div>
                </div>
                <div class="ml-[16px] flex flex-col justify-between flex-shrink-0 item">
                    <div class="text-[12px] text-[#9c9c9c] dark:text-[#707A8A]">24h成交量(USDT)</div>
                    <div class="text-[12px] mt-[6px] dark:text-[#EAECEF]">{{ priceInfo?.unitDecimals ?
                        formatNumberWithThousands(Number(coinInfo.total *
                            coinInfo.amount).toFixed(priceInfo?.unitDecimals)) :
                        formatNumberWithThousands(Number(coinInfo.total *
                            coinInfo.amount).toFixed(2)) }}</div>
                </div>
            </div>
        </div>
        <div v-show="!isLoading" class=" block sm:hidden py-[12px] h-[100%] box-border w-full">
            <div class="h-[32px] pb-[10px] flex items-center" @click="showCoinInfo">
                <div class="w-[24px] h-[24px] mr-[8px]">
                    <img :src="getSrc()" class="w-[100%] h-[100%]" />
                </div>
                <div class=" font-bold dark:text-[#EAECEF]">{{ useCoinStore().coinInfo.name
                    }}/USDT</div>
                <span class="iconfont ml-[6px] text-[10px] dark:text-[#EAECEF]" :class="['icon-xiangxia']"></span>
            </div>
            <div class="flex h-[calc(100%-40px)] justify-between">
                <div class="flex justify-between flex-col">
                    <div>
                        <div class="text-[28px] font-bold " :class="[coinInfo.percent > 0 ? 'text-rise' : 'text-fall']">
                            {{
                                coinInfo.amount }}</div>
                        <div class="text-[12px]">
                            <span class="dark:text-[#EAECEF]">${{ formatNumberWithThousands(coinInfo.externalPrice)
                            }}</span>
                            <span class="ml-[8px]" :class="[coinInfo.percent > 0 ? 'text-rise' : 'text-fall']"> {{
                                coinInfo.percent >
                                    0 ? '+' : '' }}{{ Number(coinInfo.percent *
                                    100).toFixed(2)
                                }}%</span>
                        </div>
                    </div>
                    <div @click="addLove"
                        class="w-[24px] mr-[4px] h-[24px] border-solid border-[1px] cursor-pointer border-[#ededed] dark:border-[#333b47] rounded-[6px] flex items-center justify-center">
                        <span
                            :class="[userStore().loveList.includes(useCoinStore().coinInfo.name) ? 'icon-shoucang1 text-[#f0b90b]' : 'icon-shoucang text-[#bfbfbf] dark:text-[#4f5867]']"
                            class="iconfont  text-[16px]"></span>
                    </div>
                </div>
                <div class="w-[180px] text-[12px] flex gap-[10px] flex-wrap">
                    <div class="w-[calc(40%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h最高价</div>
                    <div class="w-[calc(60%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A] ">24h成交量({{
                        useCoinStore().coinInfo.name
                    }})</div>
                    <div class="w-[calc(40%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{ coinInfo.highest
                    }}
                    </div>
                    <div class="w-[calc(60%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{ coinInfo.total
                        }}</div>
                    <div class="w-[calc(40%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h最低价</div>
                    <div class="w-[calc(60%-5px)] text-[10px] text-[#757575] dark:text-[#707A8A]">24h成交量(USDT)</div>
                    <div class="w-[calc(40%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{ coinInfo.lowest
                    }}</div>
                    <div class="w-[calc(60%-5px)] dark:text-[#EAECEF] overflow-hidden text-ellipsis">{{
                        Number(coinInfo.total *
                            coinInfo.amount).toFixed(2) }}</div>
                </div>
            </div>
        </div>
        <Loading v-show="isLoading" />
    </div>
</template>

<style scoped></style>